<?php
session_start();
require_once("includes/header.php");
?>

<?php
require 'checkFormLib.php';
$firstname = $surname = $password = $email = "";

if (!empty($_POST)) {
    $fields = array('firstname', 'surname', 'password', 'email');
    foreach ($fields as $v)
        $save_data[$v] = isset($_POST[$v]) ? test_input($_POST[$v]) : '';
}
$error = array();
$result = checkUsername($save_data['firstname']);
if ($result !== true) {
    $error['firstname'] = "first name can not be empty";
}
$result = checkUsername($save_data['surname']);
if ($result !== true) {
    $error['surname'] = "surname can not be empty";
}
$result = checkPassword($save_data['password']);
if ($result !== true) {
    $error['password'] = $result;
}
$result = checkEmail($save_data['email']);
if ($result !== true) {
    $error['email'] = $result;
}
if (empty($error)) {
    $values = array(
        "jsonFirstName" => $_POST['firstname'],
        "jsonSurName" => $_POST['surname'],
        "jsonEmail" => $_POST['email'],
        "jsonPassword" => $_POST['password']

    );
    # read the json first, then insert as email=> data pair. repeat email will update the value.
    $db = file_get_contents("data/users.json");
    $db_array = json_decode($db, true);
    $db_array[$_POST['email']] = $values;
    $json_obj = json_encode($db_array);
    file_put_contents("data/users.json", $json_obj);

    # store the username in session
    $_SESSION['username'] = $_POST['email'];

    #print welcome message and redirect
    echo "Register Success! Now redirect to MyFitness Page...";
    echo "<script language=\"JavaScript\">
window.setTimeout(\"location='index.php'\", 2000);
</script>";
} else {

    echo "Form validation failed!";
    echo "<pre>";
    foreach ($error as $key => $item) {
        echo "$item <br>";
    }
    echo "</pre>";
}

?>

<?php
require_once("includes/footer.php");
?>


